"use client";
import { DepositsTypes, RewardsType } from "@/api/depositsApi";
import { getUserMoneyApi, getUserRechargeApi } from "@/api/user";
import Box from "@/components/Box";
import ButtonOwn from "@/components/ButtonOwn";
import TipsModal, { ModalProps } from "@/components/TipsModal";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import { neReg } from "@/utils";
import { Button, Form, Input, Toast } from "antd-mobile";
import { FormInstance } from "antd-mobile/es/components/form";
import { useTranslations } from "next-intl";
import { FC, useLayoutEffect, useRef, useState } from "react";

import actions from "@/app/[locale]/(TabBar)/deposit/actions";
import Empty from "@/components/Empty";
import { useEventPoint } from "@/hooks/useEventPoint";
import { useRouter } from "@/i18n/routing";
import { useSystemStore } from "@/stores/useSystemStore";
import "@/styles/deposit.scss";
import { server } from "@/utils/client";
import clsx from "clsx";
import { Swiper, SwiperSlide } from "swiper/react";
interface Props {}

interface RewardsProps {
    rewards: RewardsType[];
}
const RewardsText: FC<RewardsProps> = (props) => {
    const { rewards } = props;
    // {/*1现金2彩金3免费币4重玩币*/}
    const t = useTranslations();
    const calcRewards = rewards
        .map((item) => {
            // let text = item.ratio > 0 ? `${item.ratio}%` : `${item.reward}`;
            // 根据coin_type添加后缀
            const suffixes = {
                1: t("ProfilePage.balance"),
                2: t("ProfilePage.bonus"),
                3: t("ProfilePage.free"),
                4: t("ProfilePage.replay"),
            };
            let text = "";
            // 设置基础奖励文本
            if (item.ratio > 0) {
                text = `${item.ratio}%`;
            } else {
                text = `${item.reward}`;
            }
            if (item.ratio > 0 && item.reward > 0) {
                text = `${item.ratio}%${suffixes[item.coin_type]}, ${item.reward}`;
            }

            // 如果coin_type在suffixes中存在，则添加相应的后缀
            if (suffixes.hasOwnProperty(item.coin_type)) {
                text += suffixes[item.coin_type];
            }

            return text;
        })
        .join(",");

    return (
        <div className={"flex flex-1 flex-wrap break-all"}>
            <span className="amountTips">+ {calcRewards} </span>
        </div>
    );
};

const getDepositApi = async () => {
    return server
        .request<DepositsTypes[]>({
            url: "/v1/api/user/user_deposit_config",
            method: "post",
            data: { activity_type: 0 },
        })
        .then((res) => {
            if (res.code === 200) return res.data;
            return [];
        });
};
const DepositData: FC<Props> = (props) => {
    const t = useTranslations();
    const router = useRouter();
    const userInfo = useUserInfoStore((state) => state.userInfo);
    const { eventInitiate } = useEventPoint();

    const isStrictMode = useSystemStore((state) => state.identity_verify.deposit === 1);

    const [depositState, setDepositState] = useState<DepositsTypes[]>([]);

    const [activeType, setActiveType] = useState<Partial<DepositsTypes>>({});

    const formInstanceRef = useRef<FormInstance>(null);
    let [amount, setAmount] = useState<number | undefined>(undefined);

    const titleChangeHandler = (item: DepositsTypes, index: number) => {
        setAmount(undefined);
        setActiveType(item);
        formInstanceRef.current?.resetFields();
    };

    const tipModelRef = useRef<ModalProps>(null); // 充值清空打码量弹窗
    const [formData, setFormData] = useState<any>({}); // 存放表单数据
    const onFinish = async (values: any) => {
        const params = { ...values, channel_id: activeType.id, amount: +values.amount };
        const res = await getUserMoneyApi();
        if (res.data?.tips_reset_rollover) {
            tipModelRef.current?.onOpen();
            setFormData(params);
            return;
        }
        handleUserRecharge(false, params);
    };

    const handleUserRecharge = (is_reset_rollover: boolean, data?: any) => {
        let params = data || formData;
        getUserRechargeApi({ is_reset_rollover, ...params })
            .then(async (res) => {
                formInstanceRef.current?.resetFields();
                // Toast.show({ icon: "success", content: t("code.200"), maskClickable: false });
                tipModelRef.current?.onClose();
                setAmount(undefined);
                // const url =
                //     "https://caixa.pay4z.com/brl/qrcode.html?tradeNo=T2501180056ijk21kJ&amount=20&payAmount=20&currency=BRL&expiredAt=2025-01-18%2001%3A11%3A31&expire=1737173491282&raw=00020101021226870014br.gov.bcb.pix2565qrcode.santsbank.com%2Fdynamic%2Fdc8cf003-1616-47f8-94e6-16be500d05b45204000053039865802BR5907LF%20LTDA6009Sao%20Paulo62070503***6304DF54&type=QRCODE";

                if (res.data.pay_url) {
                    eventInitiate();
                    // fix: ios 限制
                    setTimeout(() => {
                        window.open(res.data.pay_url);
                    }, 0);
                } else {
                    Toast.show({ icon: "success", content: t("code.200"), maskClickable: false });
                }
                const data = await getDepositApi();
                setDepositState(data);
                setActiveType(data[0]);
                await actions();
            })
            .catch((error) => {
                Toast.show({ content: t(`code.${error.data.code}`), maskClickable: false });
            });
    };

    const onValuesChange = (changeValues: any) => {
        if (changeValues.amount) {
            setAmount(changeValues.amount);
        }
    };
    const amountChange = (value: number) => {
        formInstanceRef.current?.setFieldValue("amount", value);
        setAmount(value);
    };
    const amountValidator = (rules: any, value: any) => {
        if (!value) return Promise.reject(new Error(t("form.amount")));
        if (+value < activeType.min_amount!)
            return Promise.reject(
                new Error(t("form.amountMinReg", { amount: activeType.min_amount }))
            );
        if (+value > activeType.max_amount!)
            return Promise.reject(
                new Error(t("form.amountMaxReg", { amount: activeType.max_amount }))
            );
        return Promise.resolve();
    };

    useLayoutEffect(() => {
        getDepositApi().then((data) => {
            setDepositState(data);
            setActiveType(data[0]);
        });
    }, []);

    if (!depositState.length) return <Empty />;

    return (
        <div className="deposit-box">
            <div className="img-box">
                <img
                    className={"h-[100%] w-[100%] object-cover"}
                    src={activeType.icon || ""}
                    alt={activeType.name || ""}
                    width={160}
                    height={40}
                />
            </div>

            {/*<div className={"flex flex-wrap"}>*/}
            {/*    {depositState.map((item, index) => {*/}
            {/*        return (*/}
            {/*            <Fragment key={item.id}>*/}
            {/*                <p*/}
            {/*                    className="btn-box truncate"*/}
            {/*                    style={{*/}
            {/*                        borderColor: activeType?.id === item.id ? "#ff9323" : "#333",*/}
            {/*                    }}*/}
            {/*                    onClick={() => titleChangeHandler(item, index)}*/}
            {/*                >*/}
            {/*                    {item.name}*/}
            {/*                </p>*/}
            {/*            </Fragment>*/}
            {/*        );*/}
            {/*    })}*/}
            {/*</div>*/}
            {/* {
                                background: activeType?.id === item.id ? "#d917ff" : "transparent",
                                boxShadow: activeType?.id === item.id ? "none":,
                                borderColor: activeType?.id === item.id ? "#d917ff",
                            } */}
            <Swiper slidesPerView={"auto"} centeredSlidesBounds>
                {depositState?.map((item, index) => (
                    <SwiperSlide key={index} className={"max-w-fit"}>
                        <p
                            className={clsx("btn-box truncate", {
                                active: activeType?.id === item.id, // 检查是否为当前活动项，添加active类名
                            })}
                            onClick={() => titleChangeHandler(item, index)}
                        >
                            {item.name}
                        </p>
                    </SwiperSlide>
                ))}
            </Swiper>

            <Box className={"custom-form"} style={{ padding: 0 }}>
                <Form
                    style={{
                        "--border-bottom": "none",
                        "--border-top": "none",
                        "--border-inner": "none",
                    }}
                    ref={formInstanceRef}
                    footer={
                        <>
                            <ButtonOwn active>{t("DepositPage.DepositarAgora")}</ButtonOwn>
                        </>
                    }
                    initialValues={userInfo}
                    onFinish={onFinish}
                    onValuesChange={onValuesChange}
                >
                    {isStrictMode ? (
                        <>
                            <Form.Item
                                name="user_name"
                                label=""
                                rules={[{ required: true, message: t("form.usernameReg") }]}
                            >
                                <Input placeholder={t("form.username")} />
                            </Form.Item>
                            <Form.Item
                                name="passport"
                                label=""
                                rules={[
                                    { required: true, message: t("form.cardReg"), pattern: neReg },
                                ]}
                            >
                                <Input placeholder={t("form.card")} maxLength={11} type={"text"} />
                            </Form.Item>
                        </>
                    ) : null}
                    <Form.Item
                        name="amount"
                        label=""
                        rules={[{ required: true, type: "number", validator: amountValidator }]}
                    >
                        <Input
                            placeholder={`${t("DepositPage.Montante")}: (${activeType?.min_amount}-${activeType?.max_amount})`}
                            type={"number"}
                            maxLength={activeType?.max_amount}
                        />
                    </Form.Item>

                    <div className={"flex flex-col"}>
                        <div className={"flex-1"}>
                            <ul className="ul-box">
                                {activeType?.products?.map((item, index) => (
                                    <li
                                        className={amount == item.amount ? "active" : ""}
                                        key={index}
                                        onClick={() => amountChange(item.amount)}
                                    >
                                        {!!item.badge && <span className="hot"></span>}
                                        <div className="amountContent">
                                            {/* <span className="iconfont icon-unit-brl"></span> */}
                                            <span className="iconfont">R$</span>
                                            <span> {item.amount}</span>
                                        </div>

                                        {item.rewards && (
                                            <RewardsText
                                                rewards={
                                                    item.rewards &&
                                                    item.rewards.sort(
                                                        (p, n) => p.coin_type - n.coin_type
                                                    )
                                                }
                                            />
                                        )}
                                    </li>
                                ))}
                            </ul>
                        </div>
                    </div>
                </Form>
                <div className={"mt-[5px] text-[0.12rem] text-[#3af3ff]"}>
                    {t("DepositPage.depositTips")}
                </div>
            </Box>
            <TipsModal title={"Tips"} ref={tipModelRef}>
                <div className={"flex items-center justify-between"}>
                    <h2 className={"text-[0.14rem]"}>Mantenha Bônus</h2>
                    <Button
                        color={"primary"}
                        className={"mx-auto"}
                        style={{
                            "--background-color": "var(--primary-color)",
                            "--border-color": "var(--primary-color)",
                        }}
                        onClick={() => handleUserRecharge(false)}
                    >
                        Depósito
                    </Button>
                </div>
                <p className={"mt-[0.05rem] text-left text-[0.12rem] font-medium text-[#666]"}>
                    Recarga direta, mantendo a carteira principal e informações de carteira de
                    bônus;
                </p>
                <b
                    className={"mb-[0.2rem] mt-[0.2rem]"}
                    style={{
                        width: "100%",
                        height: "auto",
                        borderTop: "1px solid #e5e5e5",
                        display: "block",
                    }}
                ></b>
                <div className={"flex items-center justify-between"}>
                    <h2 className={"text-[0.14rem]"}>Esvaziem Bônus</h2>
                    <Button
                        color={"primary"}
                        className={"mx-auto"}
                        style={{
                            "--background-color": "var(--primary-color)",
                            "--border-color": "var(--primary-color)",
                        }}
                        onClick={() => handleUserRecharge(true)}
                    >
                        Depósito
                    </Button>
                </div>
                <p className={"mt-[0.05rem] text-left text-[0.12rem] font-medium text-[#64d23e]"}>
                    Após a recarga, o saldo principal é mantido e todo o bônus é esvaziado, a nova
                    carteira principal e a carteira de bônus são re-gravadas a quantidade de códigos
                    jogados;
                </p>
            </TipsModal>
        </div>
    );
};

export default DepositData;
